<template>
  <div>
    <div>{{ place_name }}</div>
    <div id="map-container"></div>
    <!-- <div>{{ center }}</div> -->
    <!-- 显示中心经纬度 -->

    <!-- <div>{{ local_latitude }}1</div>
      <div>{{ local_longitude }}1</div> -->
  </div>
</template>

<script>
import { load } from "@amap/amap-jsapi-loader";

export default {
  props: ["local_latitude", "local_longitude"],
  data() {
    return {
      center: "", // 用于存储中心经纬度
      map: null, // 地图实例对象
      place_name: "",
      latitude: this.local_latitude,
      longitude: this.local_longitude,
    };
  },
  methods: {
    getPlaceName() {
      const params = new URLSearchParams();
      params.append("latitude", this.local_latitude);
      params.append("longitude", this.local_longitude);
      this.axios
        .post("http://127.0.0.1:8000/get_place_name/", params)
        .then((res) => {
          this.place_name = res.data.data;
          // console.log(this.place_name);
        });
    },
  },
  mounted() {
    load({
      key: "f819c82141a53cedf6c86346c694e12f",
      version: "2.0",
      plugins: ["AMap.Geolocation"],
    })
      .then((AMap) => {
        this.map = new AMap.Map("map-container", {
          center: [this.longitude, this.latitude],
          zoom: 50,
        });

        // 创建标志对象
        this.marker = new AMap.Marker({
          position: this.map.getCenter(), // 设置标志位置为地图中心点
          draggable: true, // 设置标志为可拖动
        });

        this.marker.setMap(this.map); // 将标志添加到地图上

        // 监听标志拖动事件，更新中心点坐标
        this.marker.on("dragend", (event) => {
          const center = event.target.getPosition();
          this.center = `中心经度：${center.lng}，中心纬度：${center.lat}`;
          this.longitude = center.lng;
          this.latitude = center.lat;
          this.getPlaceName();
        });

        // 监听地图移动事件，更新标志位置
        this.map.on("moveend", () => {
          const center = this.map.getCenter();
          this.marker.setPosition(center);
          this.center = `中心经度：${center.lng}，中心纬度：${center.lat}`;
          this.longitude = center.lng;
          this.latitude = center.lat;
          this.getPlaceName();
        });
      })
      .catch((error) => {
        console.log("加载高德地图失败：", error);
      });
  },
};
</script>
<style scoped>
#map-container {
  height: 200px;
  width: 384.54px;
}
</style>
